const API_BASE = 'http://localhost:5000/api';

// 显示消息提示
function showMessage(text, type = 'success') {
    const messageEl = document.getElementById('message');
    messageEl.textContent = text;
    messageEl.className = `toast-message ${type} show`;
    setTimeout(() => {
        messageEl.classList.remove('show');
    }, 3000);
}

// 显示/隐藏加载遮罩
function showLoading(show = true) {
    const overlay = document.getElementById('loadingOverlay');
    if (show) {
        overlay.classList.add('show');
    } else {
        overlay.classList.remove('show');
    }
}

// API 请求封装
async function apiRequest(endpoint, options = {}) {
    try {
        const response = await fetch(`${API_BASE}${endpoint}`, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers,
            },
            ...options,
        });
        const data = await response.json();
        if (!data.success) {
            throw new Error(data.message || '请求失败');
        }
        return data;
    } catch (error) {
        throw error;
    }
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
}

// 格式化货币
function formatCurrency(amount) {
    return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }).format(amount);
}

// 格式化数字
function formatNumber(num) {
    return new Intl.NumberFormat('zh-CN').format(num);
}

// 转义HTML
function escapeHtml(str = '') {
    return str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

// 更新当前时间
function updateCurrentTime() {
    const timeEl = document.getElementById('currentTime');
    if (timeEl) {
        const now = new Date();
        timeEl.textContent = now.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    }
}

// 加载统计数据
async function loadStats() {
    try {
        const data = await apiRequest('/stats');
        document.getElementById('totalEmployees').textContent = data.data.total_employees;
        document.getElementById('totalProducts').textContent = data.data.total_products;
        document.getElementById('lowStockCount').textContent = data.data.low_stock_count;
        document.getElementById('expiringCount').textContent = data.data.expiring_count;
    } catch (error) {
        console.error('加载统计数据失败:', error);
    }
}

// 加载员工列表
async function loadEmployees() {
    try {
        showLoading(true);
        const data = await apiRequest('/employees');
        const tbody = document.querySelector('#employeeList');
        
        if (data.data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="10" class="empty">暂无员工数据</td></tr>';
            return;
        }
        
        tbody.innerHTML = data.data.map(emp => {
            let guarantorInfo = '<span style="color: var(--text-secondary);">未设置</span>';
            if (emp.guarantor_name) {
                const dataInfo = encodeURIComponent(JSON.stringify({
                    name: emp.guarantor_name || '',
                    contact: emp.guarantor_contact || '',
                    relation: emp.guarantor_relation || '',
                }));
                guarantorInfo = `
                    <button class="guarantor-link"
                        data-guarantor="${dataInfo}"
                        onclick="showGuarantorInfo(this)">
                        ${escapeHtml(emp.guarantor_name)}
                    </button>
                `;
            }
            return `
                <tr>
                    <td><strong>${emp.employee_id}</strong></td>
                    <td>${emp.name}</td>
                    <td>${emp.role}</td>
                    <td>${emp.contact}</td>
                    <td>${formatCurrency(emp.base_salary)}</td>
                    <td>${formatNumber(emp.performance_target)}</td>
                    <td>${formatNumber(emp.performance_score)}</td>
                    <td><strong style="color: var(--primary-blue);">${formatCurrency(emp.salary)}</strong></td>
                    <td style="font-size: 13px; line-height: 1.5; white-space: normal;">${guarantorInfo}</td>
                    <td>
                        <button class="btn btn-danger-small" onclick="deleteEmployee('${emp.employee_id}', '${emp.name}')">删除</button>
                    </td>
                </tr>
            `;
        }).join('');
    } catch (error) {
        showMessage('加载员工列表失败: ' + error.message, 'error');
        const tbody = document.querySelector('#employeeList');
        tbody.innerHTML = '<tr><td colspan="10" class="empty">加载失败</td></tr>';
    } finally {
        showLoading(false);
    }
}

// 加载薪资报告
async function loadPayroll() {
    try {
        showLoading(true);
        const data = await apiRequest('/employees');
        const tbody = document.querySelector('#payrollList');
        
        if (data.data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="6" class="empty">暂无员工数据</td></tr>';
            return;
        }
        
        tbody.innerHTML = data.data.map(emp => `
            <tr>
                <td><strong>${emp.employee_id}</strong></td>
                <td>${emp.name}</td>
                <td>${emp.role}</td>
                <td>${formatNumber(emp.performance_target)}</td>
                <td>${formatNumber(emp.performance_score)}</td>
                <td><strong style="color: var(--primary-blue);">${formatCurrency(emp.salary)}</strong></td>
            </tr>
        `).join('');
    } catch (error) {
        console.error('加载薪资报告失败:', error);
        const tbody = document.querySelector('#payrollList');
        tbody.innerHTML = '<tr><td colspan="6" class="empty">加载失败</td></tr>';
    } finally {
        showLoading(false);
    }
}

// 加载产品列表
async function loadProducts() {
    try {
        showLoading(true);
        const data = await apiRequest('/products');
        const tbody = document.querySelector('#productList');
        
        if (data.data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="9" class="empty">暂无产品数据</td></tr>';
            return;
        }
        
        tbody.innerHTML = data.data.map(prod => {
            let statusBadge = '<span class="status-badge success">正常</span>';
            if (prod.needs_expiry_warning && prod.needs_restock) {
                statusBadge = '<span class="status-badge danger">过期+缺货</span>';
            } else if (prod.needs_expiry_warning) {
                statusBadge = '<span class="status-badge warning">即将过期</span>';
            } else if (prod.needs_restock) {
                statusBadge = '<span class="status-badge danger">库存不足</span>';
            }
            
            return `
                <tr>
                    <td><strong>${prod.sku}</strong></td>
                    <td>${prod.name}</td>
                    <td>${prod.category}</td>
                    <td><strong style="color: var(--primary-blue);">${formatCurrency(prod.price || 200)}</strong></td>
                    <td>${formatNumber(prod.quantity)}</td>
                    <td>${formatNumber(prod.reorder_threshold)}</td>
                    <td>${formatDate(prod.expires_on)}</td>
                    <td>${statusBadge}</td>
                    <td>
                        <button class="btn btn-danger-small" onclick="deleteProduct('${prod.sku}', '${prod.name}')">删除</button>
                    </td>
                </tr>
            `;
        }).join('');
    } catch (error) {
        showMessage('加载产品列表失败: ' + error.message, 'error');
        const tbody = document.querySelector('#productList');
        tbody.innerHTML = '<tr><td colspan="7" class="empty">加载失败</td></tr>';
    } finally {
        showLoading(false);
    }
}

// 加载库存概览
async function loadInventory() {
    try {
        showLoading(true);
        const data = await apiRequest('/products');
        const tbody = document.querySelector('#inventoryList');
        
        if (data.data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" class="empty">暂无产品数据</td></tr>';
            return;
        }
        
        tbody.innerHTML = data.data.map(prod => `
            <tr>
                <td><strong>${prod.sku}</strong></td>
                <td>${prod.name}</td>
                <td>${prod.category}</td>
                <td><strong style="color: var(--primary-blue);">${formatCurrency(prod.price || 200)}</strong></td>
                <td>${formatNumber(prod.quantity)}</td>
                <td>${formatNumber(prod.reorder_threshold)}</td>
                <td>${formatDate(prod.expires_on)}</td>
            </tr>
        `).join('');
    } catch (error) {
        console.error('加载库存概览失败:', error);
        const tbody = document.querySelector('#inventoryList');
        tbody.innerHTML = '<tr><td colspan="7" class="empty">加载失败</td></tr>';
    } finally {
        showLoading(false);
    }
}

// 加载即将过期的产品
async function loadExpiringProducts() {
    try {
        showLoading(true);
        const data = await apiRequest('/alerts/expiring');
        const tbody = document.querySelector('#expiringList');
        const badge = document.getElementById('expiringBadge');
        
        if (badge) {
            badge.textContent = data.data.length;
        }
        
        if (data.data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="3" class="empty">暂无即将过期的产品</td></tr>';
            return;
        }
        
        tbody.innerHTML = data.data.map(prod => `
            <tr>
                <td><strong>${prod.sku}</strong></td>
                <td>${prod.name}</td>
                <td><span class="status-badge warning">${formatDate(prod.expires_on)}</span></td>
            </tr>
        `).join('');
    } catch (error) {
        showMessage('加载过期产品失败: ' + error.message, 'error');
        const tbody = document.querySelector('#expiringList');
        tbody.innerHTML = '<tr><td colspan="3" class="empty">加载失败</td></tr>';
    } finally {
        showLoading(false);
    }
}

// 加载低库存产品
async function loadLowStockProducts() {
    try {
        showLoading(true);
        const data = await apiRequest('/alerts/low-stock');
        const tbody = document.querySelector('#lowStockList');
        const badge = document.getElementById('lowStockBadge');
        
        if (badge) {
            badge.textContent = data.data.length;
        }
        
        if (data.data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="4" class="empty">所有库存充足</td></tr>';
            return;
        }
        
        tbody.innerHTML = data.data.map(prod => `
            <tr>
                <td><strong>${prod.sku}</strong></td>
                <td>${prod.name}</td>
                <td><strong style="color: var(--danger-red);">${formatNumber(prod.quantity)}</strong></td>
                <td>${formatNumber(prod.reorder_threshold)}</td>
            </tr>
        `).join('');
    } catch (error) {
        showMessage('加载低库存产品失败: ' + error.message, 'error');
        const tbody = document.querySelector('#lowStockList');
        tbody.innerHTML = '<tr><td colspan="4" class="empty">加载失败</td></tr>';
    } finally {
        showLoading(false);
    }
}

// 刷新当前标签页数据
function refreshCurrentTab() {
    const activeTab = document.querySelector('.nav-item.active')?.dataset.tab;
    if (!activeTab) return;
    
    loadStats();
    
    switch (activeTab) {
        case 'dashboard':
            loadPayroll();
            loadInventory();
            break;
        case 'employees':
            loadEmployees();
            break;
        case 'products':
            loadProducts();
            break;
        case 'alerts':
            loadExpiringProducts();
            loadLowStockProducts();
            break;
        case 'analysis':
            loadSalesAnalysis();
            loadEmployeeQualityAnalysis();
            break;
        case 'history':
            loadSalesHistory();
            break;
    }
}

// 标签页切换
document.querySelectorAll('.nav-item').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.nav-item').forEach(b => b.classList.remove('active'));
        document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
        
        btn.classList.add('active');
        const tabId = btn.dataset.tab;
        document.getElementById(tabId).classList.add('active');
        refreshCurrentTab();
    });
});

// 添加员工表单
document.getElementById('addEmployeeForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        showLoading(true);
        await apiRequest('/employees', {
            method: 'POST',
            body: JSON.stringify({
                employee_id: document.getElementById('empId').value.trim(),
                name: document.getElementById('empName').value.trim(),
                role: document.getElementById('empRole').value.trim(),
                contact: document.getElementById('empContact').value.trim(),
                base_salary: parseFloat(document.getElementById('empSalary').value),
                performance_target: parseFloat(document.getElementById('empTarget').value),
                guarantor_name: document.getElementById('empGuarantorName').value.trim(),
                guarantor_contact: document.getElementById('empGuarantorContact').value.trim(),
                guarantor_relation: document.getElementById('empGuarantorRelation').value.trim(),
            }),
        });
        showMessage('员工添加成功', 'success');
        e.target.reset();
        refreshCurrentTab();
    } catch (error) {
        showMessage('添加失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
});

// 更新员工信息表单
document.getElementById('updateEmployeeForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        showLoading(true);
        const employeeId = document.getElementById('updateEmpId').value.trim();
        const updateData = {};
        
        const role = document.getElementById('updateEmpRole').value.trim();
        const contact = document.getElementById('updateEmpContact').value.trim();
        const salary = document.getElementById('updateEmpSalary').value.trim();
        const target = document.getElementById('updateEmpTarget').value.trim();
        const guarantorName = document.getElementById('updateGuarantorName').value.trim();
        const guarantorContact = document.getElementById('updateGuarantorContact').value.trim();
        const guarantorRelation = document.getElementById('updateGuarantorRelation').value.trim();
        
        if (role) updateData.role = role;
        if (contact) updateData.contact = contact;
        if (salary) updateData.base_salary = parseFloat(salary);
        if (target) updateData.performance_target = parseFloat(target);
        if (guarantorName) updateData.guarantor_name = guarantorName;
        if (guarantorContact) updateData.guarantor_contact = guarantorContact;
        if (guarantorRelation) updateData.guarantor_relation = guarantorRelation;
        
        await apiRequest(`/employees/${employeeId}`, {
            method: 'PUT',
            body: JSON.stringify(updateData),
        });
        showMessage('员工信息更新成功', 'success');
        e.target.reset();
        refreshCurrentTab();
    } catch (error) {
        showMessage('更新失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
});

// 更新绩效表单
document.getElementById('updatePerformanceForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        showLoading(true);
        const employeeId = document.getElementById('perfEmpId').value.trim();
        await apiRequest(`/employees/${employeeId}/performance`, {
            method: 'POST',
            body: JSON.stringify({
                delta: parseFloat(document.getElementById('perfDelta').value),
            }),
        });
        showMessage('绩效更新成功', 'success');
        e.target.reset();
        refreshCurrentTab();
    } catch (error) {
        showMessage('更新失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
});

// 添加产品表单
document.getElementById('addProductForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        showLoading(true);
        await apiRequest('/products', {
            method: 'POST',
            body: JSON.stringify({
                sku: document.getElementById('prodSku').value.trim(),
                name: document.getElementById('prodName').value.trim(),
                category: document.getElementById('prodCategory').value.trim(),
                quantity: parseInt(document.getElementById('prodQuantity').value),
                reorder_threshold: parseInt(document.getElementById('prodThreshold').value),
                expires_on: document.getElementById('prodExpiry').value,
                price: parseFloat(document.getElementById('prodPrice').value),
            }),
        });
        showMessage('产品添加成功', 'success');
        e.target.reset();
        refreshCurrentTab();
    } catch (error) {
        showMessage('添加失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
});

// 补货表单
document.getElementById('restockForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        showLoading(true);
        const sku = document.getElementById('restockSku').value.trim();
        const quantity = parseInt(document.getElementById('restockQuantity').value);
        const expiryDate = document.getElementById('restockExpiry').value.trim();
        const priceValue = document.getElementById('restockPrice').value.trim();
        
        const requestData = {
            quantity: quantity,
        };
        
        // 如果填写了过期日期，则一起更新
        if (expiryDate) {
            requestData.expires_on = expiryDate;
        }
        
        // 如果填写了单价，则一起更新
        if (priceValue) {
            requestData.price = parseFloat(priceValue);
        }
        
        await apiRequest(`/products/${sku}/restock`, {
            method: 'POST',
            body: JSON.stringify(requestData),
        });
        
        let message = '补货成功';
        const updates = [];
        if (expiryDate) updates.push('过期日期已更新');
        if (priceValue) updates.push('单价已更新');
        if (updates.length > 0) {
            message += '，' + updates.join('、');
        }
        
        showMessage(message, 'success');
        e.target.reset();
        refreshCurrentTab();
    } catch (error) {
        showMessage('补货失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
});

// 销售记录表单
document.getElementById('saleForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        showLoading(true);
        const employeeId = document.getElementById('saleEmployeeId').value.trim();
        await apiRequest('/sales', {
            method: 'POST',
            body: JSON.stringify({
                sku: document.getElementById('saleSku').value.trim(),
                quantity: parseInt(document.getElementById('saleQuantity').value),
                employee_id: employeeId || null,
            }),
        });
        showMessage('销售记录成功', 'success');
        e.target.reset();
        refreshCurrentTab();
    } catch (error) {
        showMessage('记录失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
});

// 删除员工
async function deleteEmployee(employeeId, name) {
    if (!confirm(`确定要删除员工 "${name}" (${employeeId}) 吗？此操作不可恢复。`)) {
        return;
    }
    try {
        showLoading(true);
        await apiRequest(`/employees/${employeeId}`, { method: 'DELETE' });
        showMessage('员工删除成功', 'success');
        refreshCurrentTab();
    } catch (error) {
        showMessage('删除失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
}

// 删除产品
async function deleteProduct(sku, name) {
    if (!confirm(`确定要删除产品 "${name}" (${sku}) 吗？此操作不可恢复。`)) {
        return;
    }
    try {
        showLoading(true);
        await apiRequest(`/products/${sku}`, { method: 'DELETE' });
        showMessage('产品删除成功', 'success');
        refreshCurrentTab();
    } catch (error) {
        showMessage('删除失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
}

// 加载销售分析
async function loadSalesAnalysis() {
    try {
        showLoading(true);
        const data = await apiRequest('/analysis/sales');
        const container = document.getElementById('salesAnalysisContent');
        
        const analysis = data.data;
        let html = `
            <div style="margin-bottom: 20px;">
                <h4 style="margin-bottom: 12px; color: var(--text-primary);">总体统计</h4>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; margin-bottom: 20px;">
                    <div style="padding: 16px; background: var(--bg-tertiary); border-radius: 6px;">
                        <div style="font-size: 12px; color: var(--text-secondary); margin-bottom: 4px;">总销量</div>
                        <div style="font-size: 24px; font-weight: 600; color: var(--primary-blue);">${formatNumber(analysis.total_sales)}</div>
                    </div>
                    <div style="padding: 16px; background: var(--bg-tertiary); border-radius: 6px;">
                        <div style="font-size: 12px; color: var(--text-secondary); margin-bottom: 4px;">总销售额</div>
                        <div style="font-size: 24px; font-weight: 600; color: var(--success-green);">${formatCurrency(analysis.total_revenue)}</div>
                    </div>
                </div>
            </div>
        `;
        
        // 按产品统计
        if (Object.keys(analysis.by_product).length > 0) {
            html += `
                <div style="margin-bottom: 20px;">
                    <h4 style="margin-bottom: 12px; color: var(--text-primary);">产品销量排行</h4>
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>SKU</th>
                                    <th>产品名称</th>
                                    <th>销量</th>
                                    <th>销售额</th>
                                </tr>
                            </thead>
                            <tbody>
            `;
            const sortedProducts = Object.entries(analysis.by_product)
                .sort((a, b) => b[1].quantity - a[1].quantity)
                .slice(0, 10);
            sortedProducts.forEach(([sku, data]) => {
                html += `
                    <tr>
                        <td><strong>${sku}</strong></td>
                        <td>${data.name}</td>
                        <td>${formatNumber(data.quantity)}</td>
                        <td>${formatCurrency(data.revenue)}</td>
                    </tr>
                `;
            });
            html += `
                            </tbody>
                        </table>
                    </div>
                </div>
            `;
        }
        
        // 按类别统计
        if (Object.keys(analysis.by_category).length > 0) {
            html += `
                <div style="margin-bottom: 20px;">
                    <h4 style="margin-bottom: 12px; color: var(--text-primary);">类别销量统计</h4>
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>类别</th>
                                    <th>销量</th>
                                    <th>销售额</th>
                                </tr>
                            </thead>
                            <tbody>
            `;
            Object.entries(analysis.by_category)
                .sort((a, b) => b[1].quantity - a[1].quantity)
                .forEach(([category, data]) => {
                    html += `
                        <tr>
                            <td><strong>${category}</strong></td>
                            <td>${formatNumber(data.quantity)}</td>
                            <td>${formatCurrency(data.revenue)}</td>
                        </tr>
                    `;
                });
            html += `
                            </tbody>
                        </table>
                    </div>
                </div>
            `;
        }
        
        container.innerHTML = html;
    } catch (error) {
        showMessage('加载销售分析失败: ' + error.message, 'error');
        document.getElementById('salesAnalysisContent').innerHTML = '<div class="empty">加载失败</div>';
    } finally {
        showLoading(false);
    }
}

// 加载员工质量分析
async function loadEmployeeQualityAnalysis() {
    try {
        showLoading(true);
        const data = await apiRequest('/analysis/employee-quality');
        const tbody = document.querySelector('#qualityAnalysisList');
        
        if (data.data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" class="empty">暂无数据</td></tr>';
            return;
        }
        
        tbody.innerHTML = data.data.map(item => {
            let gradeClass = 'success';
            if (item.quality_grade === '待改进') gradeClass = 'danger';
            else if (item.quality_grade === '合格') gradeClass = 'warning';
            
            return `
                <tr>
                    <td><strong>${item.employee_id}</strong></td>
                    <td>${item.name}</td>
                    <td>${item.role}</td>
                    <td>${formatNumber(item.total_sales)}</td>
                    <td>${formatCurrency(item.total_revenue)}</td>
                    <td>
                        <span class="status-badge ${gradeClass}">${item.completion_rate}%</span>
                    </td>
                    <td>
                        <span class="status-badge ${gradeClass}">${item.quality_grade}</span>
                    </td>
                    <td><strong style="color: var(--primary-blue);">${formatCurrency(item.actual_salary)}</strong></td>
                </tr>
            `;
        }).join('');
    } catch (error) {
        showMessage('加载质量分析失败: ' + error.message, 'error');
        const tbody = document.querySelector('#qualityAnalysisList');
        tbody.innerHTML = '<tr><td colspan="8" class="empty">加载失败</td></tr>';
    } finally {
        showLoading(false);
    }
}

// 加载销售历史
let allSalesHistory = [];
async function loadSalesHistory() {
    try {
        showLoading(true);
        const data = await apiRequest('/sales/history?limit=500');
        allSalesHistory = data.data;
        displaySalesHistory(allSalesHistory);
    } catch (error) {
        showMessage('加载销售历史失败: ' + error.message, 'error');
        const tbody = document.querySelector('#salesHistoryList');
        tbody.innerHTML = '<tr><td colspan="7" class="empty">加载失败</td></tr>';
    } finally {
        showLoading(false);
    }
}

// 显示销售历史
function displaySalesHistory(sales) {
    const tbody = document.querySelector('#salesHistoryList');
    
    if (sales.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="empty">暂无销售记录</td></tr>';
        return;
    }
    
    tbody.innerHTML = sales.map(sale => `
        <tr>
            <td><small>${sale.sale_id}</small></td>
            <td><strong>${sale.sku}</strong></td>
            <td>${sale.product_name}</td>
            <td>${formatNumber(sale.quantity)}</td>
            <td>${formatCurrency(sale.revenue)}</td>
            <td>${sale.employee_id || '-'}</td>
            <td>${formatDate(sale.sale_date)}</td>
        </tr>
    `).join('');
}

// 筛选销售历史
function filterSalesHistory() {
    const searchTerm = document.getElementById('historySearch').value.toLowerCase();
    const filtered = allSalesHistory.filter(sale => 
        sale.sku.toLowerCase().includes(searchTerm) ||
        sale.product_name.toLowerCase().includes(searchTerm) ||
        (sale.employee_id && sale.employee_id.toLowerCase().includes(searchTerm))
    );
    displaySalesHistory(filtered);
}

// 显示担保人信息
function showGuarantorInfo(button) {
    try {
        const info = JSON.parse(decodeURIComponent(button.dataset.guarantor || '{}'));
        const lines = [
            `担保人：${info.name || '未填写'}`,
            `关系：${info.relation || '未填写'}`,
            `联系方式：${info.contact || '未填写'}`,
        ];
        alert(lines.join('\n'));
    } catch (error) {
        console.error('无法解析担保人信息', error);
        alert('未能获取担保人信息');
    }
}

// 导出员工薪资表
async function exportPayroll() {
    try {
        showLoading(true);
        const response = await fetch(`${API_BASE}/export/payroll`);
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `员工薪资表_${new Date().toISOString().slice(0, 10)}.csv`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
        showMessage('导出成功', 'success');
    } catch (error) {
        showMessage('导出失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
}

// 导出销量分析
async function exportSalesAnalysis() {
    try {
        showLoading(true);
        const response = await fetch(`${API_BASE}/export/sales-analysis`);
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `产品销量分析_${new Date().toISOString().slice(0, 10)}.csv`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
        showMessage('导出成功', 'success');
    } catch (error) {
        showMessage('导出失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
}

// 导出员工质量分析
async function exportEmployeeQuality() {
    try {
        showLoading(true);
        const response = await fetch(`${API_BASE}/export/employee-quality`);
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `员工工作质量分析_${new Date().toISOString().slice(0, 10)}.csv`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
        showMessage('导出成功', 'success');
    } catch (error) {
        showMessage('导出失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
}

// 全局函数
window.refreshCurrentTab = refreshCurrentTab;
window.deleteEmployee = deleteEmployee;
window.deleteProduct = deleteProduct;
window.filterSalesHistory = filterSalesHistory;
window.exportPayroll = exportPayroll;
window.exportSalesAnalysis = exportSalesAnalysis;
window.exportEmployeeQuality = exportEmployeeQuality;
window.showGuarantorInfo = showGuarantorInfo;

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    updateCurrentTime();
    setInterval(updateCurrentTime, 1000);
    
    refreshCurrentTab();
    
    // 每30秒自动刷新统计数据
    setInterval(loadStats, 30000);
});
